package com.healthcloud.controller.modules.rent;

import com.healthcloud.annotation.SysLog;
import com.healthcloud.controller.modules.common.BaseController;
import com.healthcloud.entity.*;
import com.healthcloud.exception.ReturnException;
import com.healthcloud.service.*;
import com.healthcloud.utils.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 租赁
 *
 * @author zj
 * 2017年6月23日 上午9:13:25
 */
@Controller
@RequestMapping(value = "/rent")
public class BusRentController extends BaseController {

    @Autowired
    private BusRentService busRentService;

    @Autowired
    private HlHospitalService hlHospitalService;

    @Autowired
    private PpPatientBaseService ppPatientBaseService;

    @Autowired
    private HlDoctorService hlDoctorService;

    @Autowired
    private CommonMethod commonMethod;

    @ApiOperation(value = "跳转到租赁列表页")
    @RequiresPermissions("rent:list")
    @RequestMapping(value = "/toRentMgr", method = RequestMethod.GET)
    public String toRentMgr() {
        return "bus/rentmgr";
    }


    @ApiOperation(value = "租赁列表查询")
    @RequiresPermissions("rent:list")
    @RequestMapping(value = "/searchRent", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> searchRent(BusRentEntity bean, @ModelAttribute("pageParam") PageParam pageParam) {

        String ids = hlHospitalService.getChildeIds();
        bean.setHospIds(ids);

        List<BusRentEntity> list = busRentService.search(bean, pageParam);
        List<BusRentEntityVo> rentBeanVos = new ArrayList();

        toBusRentEntityWare(list, rentBeanVos);

        int count = busRentService.count(bean);
        Map<String, Object> map = new HashMap();
        map.put("dataList", rentBeanVos);
        map.put("iTotalRecords", count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }

    @RequiresPermissions("rent:list")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> list(BusRentEntity bean, @ModelAttribute("pageParam") PageParam pageParam) {
        List<BusRentEntity> list = busRentService.queryList(bean, pageParam);
        int total = busRentService.queryTotal(bean);
        Map<String, Object> map = new HashMap();
        map.put("list", list);
        map.put("iTotalDisplayRecords", total);
        return map;
    }

    @RequiresPermissions("rent:rent")
    @RequestMapping(value = "/toRent", method = RequestMethod.GET)
    public String toRent(Model model) {
        getHospitals(model);
        if (CommonMethod.hasSuperRole()){
            List<HlHospitalEntity> hospitalList = hlHospitalService.queryList(new HlHospitalEntity(), new PageParam());
            model.addAttribute("hospitalList", hospitalList);
        }
        return "bus/rentinfo";
    }

    @RequiresPermissions("rent:rent")
    @SysLog("租赁")
    @RequestMapping(value = "/addRent", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes addRent(BusRentEntity bean) throws ReturnException {
        IdCardUtil.validate(bean.getIdCard());
        busRentService.createRent(bean);

        //建档
        PpPatientBaseEntity patient = ppPatientBaseService.queryByIdcard(bean.getIdCard());
        if (patient!=null&&patient.getHospitalId()==null) {
            patient.setHospitalId(bean.getHospId());
            HlDoctorEntity doctor = hlDoctorService.queryByUserId(ShiroUtils.getUserId());
            if (doctor!=null) {
                patient.setDoctorId(doctor.getId());
            }
            ppPatientBaseService.update(patient);
        }
        return new ApiRes(true, bean, null, null);
    }

    @RequiresPermissions("rent:back")
    @RequestMapping(value = "/toBack", method = RequestMethod.GET)
    public String toBack(Long id, Model model) {
        getHospitals(model);
        BusRentEntity entity = busRentService.searchById(id);
        model.addAttribute("entity", entity);

        if (CommonMethod.hasSuperRole()) {
            List<HlHospitalEntity> hospitalList = hlHospitalService.searchAll();
            model.addAttribute("hospitalList", hospitalList);
        }
        return "bus/backinfo";
    }

    @RequiresPermissions("rent:back")
    @SysLog("归还")
    @RequestMapping(value = "/updateBack", method = RequestMethod.POST)
    public @ResponseBody
    ApiRes updateBack(BusRentEntity bean) {
        BusRentEntity oldRent = busRentService.searchById(bean.getRentId());
        if (oldRent != null && StringUtils.isNotEmpty(oldRent.getBackStatus())) {
            throw new RRException("设备已归还，请勿重复归还！");
        }
        busRentService.updateBack(bean);
        return new ApiRes(true, null, null, null);
    }

    @RequiresPermissions("rent:history:list")
    @RequestMapping(value = "/toRentHistory", method = RequestMethod.GET)
    public String toHistory(Long id, Model model) {
        getHospitals(model);

        if (CommonMethod.hasSuperRole()) {
//            List<HlHospitalEntity> hospitalList = hlHospitalService.searchAll();
            model.addAttribute("hospitalList", new ArrayList<>());
        }
        BusRentEntity entity = busRentService.searchById(id);
        model.addAttribute("entity", entity);
        BusRentEntity lastRent = busRentService.searchLastByInstrumentId(entity.getInstrumentId());
        model.addAttribute("lastRent", lastRent);
        return "bus/renthistory";
    }

    @RequiresPermissions("rent:history:update")
    @RequestMapping(value = "/updateHistory", method = RequestMethod.POST)
    public @ResponseBody
    ApiRes updateHistory(BusRentEntity bean) throws ReturnException {
        IdCardUtil.validate(bean.getIdCard());
        busRentService.updateHistory(bean);
        return new ApiRes(true, null, null, null);
    }

    @RequiresPermissions("rent:history:list")
    @RequestMapping(value = "/toDueRemind", method = RequestMethod.GET)
    public String toDueRemind(String id, Model model) {
        return "bus/duemind";
    }

    @ResponseBody
    @RequiresPermissions("rent:history:list")
    @RequestMapping(value = "/searchDue", method = RequestMethod.POST)
    public Map<String, Object> searchDue(BusRentEntity bean,
                                         Model model, @ModelAttribute("pageParam") PageParam pageParam) {

        List<BusRentEntity> list = busRentService.searchDue(bean, pageParam);

        List<BusRentEntityVo> rentBeanVos = new ArrayList();
        toBusRentEntityWare(list, rentBeanVos);

        int count = busRentService.countDue(bean);
        Map<String, Object> map = new HashMap();
        map.put("dataList", rentBeanVos);
        map.put("iTotalRecords", count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }

    @RequiresPermissions("rent:history:list")
    @RequestMapping(value = "/toCount", method = RequestMethod.GET)
    public String toCount() {
        return "admin/rent/rentalStatistical";
    }

    @ResponseBody
    @RequiresPermissions("rent:history:list")
    @RequestMapping(value = "/count", method = RequestMethod.POST)
    public ApiRes count(BusRentEntity entity) {
        String ids = hlHospitalService.getChildeIds();
        entity.setHospIds(ids);
        Map map = busRentService.countTimes(entity);
        return new ApiRes(map);
    }


    @ApiOperation(value = "获取打印信息")
    @RequestMapping(value = "/printInfo",method = RequestMethod.POST)
    @ResponseBody
    public ApiRes printInfo(Long id){

        BusRentEntity rent = busRentService.searchById(id);

        HlHospitalEntity hospital = hlHospitalService.queryObject(rent.getHospId());
        if (hospital==null){
            return ApiRes.ERROR;
        }

        Map<String, Object> data = new HashMap<>();
        data.put("date", DateUtils.format(new Date(), DateUtils.DATE_PATTERN));
        data.put("hospitalName", hospital.getHospName());
        data.put("rentMan", rent.getRentMan());
        data.put("idCard", rent.getIdCard());
        return new ApiRes(data);
    }


    @ApiOperation(value = "跳转到打印页")
    @RequestMapping(value = "/toPrint",method = RequestMethod.GET)
    public String toPrint(){
        return "bus/rent/print";
    }

    private void toBusRentEntityWare(List<BusRentEntity> list, List<BusRentEntityVo> rentBeanVos) {

        for (BusRentEntity rentBean : list) {
            Long hospId = rentBean.getHospId();
            HlHospitalEntity hospitalEntity = hlHospitalService.queryObject(hospId);
            BusRentEntityVo rentBeanVo = new BusRentEntityVo();
            BeanUtils.copyProperties(rentBean, rentBeanVo);
            if (hospitalEntity != null) {
                rentBeanVo.setHospShortName(hospitalEntity.getHospShortName());
            }
            rentBeanVos.add(rentBeanVo);
        }
    }


    private void getHospitals(Model model) {
        model.addAttribute("hospital", commonMethod.getHospitalBean());
    }

}
